﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ganss.XSS;
using Lk.Common;
using Lk.Common.Cache;
using Lk.Common.Helper;
using Lk.Common.Redis;
using Lk.Data;
using Lk.IRepositories;
using Lk.IServices;
using Lk.Repositories;
using Lk.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using static System.Net.Mime.MediaTypeNames;

namespace Lk.Web
{
    public class Startup
    {
        private readonly DataBaseProvider _dataBaseProvider;
        private readonly CacheProvider _cacheProvider;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            _dataBaseProvider = new DataBaseProvider();
            _cacheProvider = new CacheProvider();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            #region 数据库链接
            //const string connection = @"Server=.;Database=data_lkcore;Uid=sa;pwd=111";
            ////services.AddDbContext<ApplicationDbContext>(
            ////    options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
            //services.AddDbContext<ApplicationDbContext>(
            //  options => options.UseSqlServer(connection));
            if (_dataBaseProvider._isSqlServer)
            {
                services.AddDbContext<ApplicationDbContext>(
                    options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
            }
            else
            {
                if (_dataBaseProvider._isMySql)
                {
                    services.AddDbContext<ApplicationDbContext>(
                  options => options.UseMySql(Configuration.GetConnectionString("MySqlServerConnection")));
                }
                if (_dataBaseProvider._isOracle)
                {
                    //
                }
            }
            #endregion
            #region 缓存选择
            services.AddMemoryCache();
            if (_cacheProvider.UseRedis)
            {
                services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions
                {
                    Configuration = _cacheProvider.RedisConnectionString,
                    InstanceName = _cacheProvider.RedisInstanceName

                }, 0));
            }
            else
            {
                services.AddSingleton<IMemoryCache>(factory =>
                {
                    var cache = new MemoryCache(new MemoryCacheOptions());
                    return cache;
                });
                services.AddSingleton<ICacheService, MemoryCacheService>();
            }
            #endregion
    

           
            services.Configure<ApplicationConfiguration>(Configuration.GetSection("ApplicationConfiguration"));


            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
       o.Cookie.Name = "_AdminTicketCookie";
       o.LoginPath = new PathString("/Account/Login");
       o.LogoutPath = new PathString("/Account/Login");
       o.AccessDeniedPath = new PathString("/Error/Forbidden");
   });

            //services.AddTransient<IUserManage, UserManage>();
            services.AddTransient<AppConfigurtaionServices, AppConfigurtaionServices>();
            services.AddTransient<XSSHelper, XSSHelper>();
            services.AddTransient<HtmlSanitizer, HtmlSanitizer>();

            services.AddTransient<IUserService, UserService>();

            services.AddTransient<IUserRepository, UserRepository>();
            
            services.AddMvc();



        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseWkMnvDI();
            app.UseStatusCodePagesWithReExecute("/error/{0}");

            app.UseAuthentication();//添加认证中间件
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
